﻿using System;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace Wusong.Gold.DataService
{
    public class DataBaseWriter : IWriterBase, IDisposable
    {
        //Data Source=HP-WUSONG-018;Initial Catalog=Gold;Persist Security Info=True;User ID=sa;Password=123456
        private string _connetionStr;
        private DbConnection _connection;

        public DataBaseWriter(string connctionStr)
        {
            _connetionStr = connctionStr;
            try
            {
                _connection = new SqlConnection(connctionStr);
                _connection.Open();
            }
            catch (DbException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void Write(GoldMsg value)
        {
            try
            {
                GoldMsg msg = value;
                DbCommand command = _connection.CreateCommand();
                command.CommandType = CommandType.Text;

                //command.CommandText = "SaveGoldTranMsg";
                command.CommandText = "insert into GoldTranMsg(MsgTime,MidPrice,SalePrice,BuyPrice,DollarPrice,DollarIndex,OilIndex)"+
                                       "values(@P_MsgTime,@P_MidPrice,@P_SalePrice,@P_BuyPrice,@P_DollarPrice,@P_DollarIndex,@P_OilIndex)";
                SqlParameter paramter = new SqlParameter("@P_MsgTime", SqlDbType.DateTime);
                paramter.Value = msg.MsgTime;
                command.Parameters.Add(paramter);

                paramter = new SqlParameter("@P_MidPrice", SqlDbType.Float);
                paramter.Value = msg.MidPrice;

                command.Parameters.Add(paramter);
                paramter = new SqlParameter("@P_SalePrice", SqlDbType.Float);
                paramter.Value = msg.SalePrice;
                command.Parameters.Add(paramter);

                paramter = new SqlParameter("@P_BuyPrice", SqlDbType.Float);
                paramter.Value = msg.BuyPrice;
                command.Parameters.Add(paramter);

                paramter = new SqlParameter("@P_DollarPrice", SqlDbType.Float);
                paramter.Value = msg.DollarPrice;
                command.Parameters.Add(paramter);

                paramter = new SqlParameter("@P_DollarIndex", SqlDbType.Float);
                paramter.Value = msg.DollarIndex;
                command.Parameters.Add(paramter);

                paramter = new SqlParameter("@P_OilIndex", SqlDbType.Float);
                paramter.Value = msg.OilIndex;
                command.Parameters.Add(paramter);
                command.ExecuteNonQuery();


            }
            catch (DataException dtEx)
            {
                Console.WriteLine(dtEx.Message);
                Dispose();
            }
        }

        public void Dispose()
        {
            _connection.Dispose();
        }

    }

}
